package com.mix;

import com.aspose.pdf.*;
import com.aspose.pdf.facades.EncodingType;
import com.aspose.pdf.facades.FontStyle;
import com.aspose.pdf.facades.FormattedText;
import com.aspose.words.Document;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Date;

public class AsposePdfUtil {

    public static void main(String[] args) throws Exception {
        putWatermark();
    }

    // 比较Word
    public static void compareWord() throws Exception {
        // 创建一个新的文档
        Document doc1 = new Document("classpath:" + "files\\比较两个word文件的差异\\原版.docx");
        Document doc2 = new Document("classpath:" + "files\\比较两个word文件的差异\\修订版.docx");
        doc1.compare(doc2, "小明", new Date());
        // 保存文档
        doc1.save("classpath:" + "files\\比较两个word文件的差异\\比较结果.docx");
    }

    // 给Workbook加上水印
    private static void putWatermark() throws Exception {
        InputStream in = new FileInputStream("E:/demo/demo.pdf");
        com.aspose.pdf.Document doc = new com.aspose.pdf.Document(in);
        FormattedText formattedText = new FormattedText("水印内容", java.awt.Color.RED, FontStyle.HelveticaBold, EncodingType.Identity_h, true, 24f);
        for (Page page : doc.getPages()) {
            WatermarkArtifact artifact = new WatermarkArtifact();
            artifact.setText(formattedText);
            artifact.getTextState().setFont(FontRepository.findFont(getFontName("宋体"), true));
            artifact.setArtifactHorizontalAlignment(HorizontalAlignment.Center);
            artifact.setArtifactVerticalAlignment(VerticalAlignment.Center);
            artifact.setRotation(45); // 设置旋转角度
            artifact.setOpacity(0.9); // 设置透明度
            artifact.setBackground(true);
            page.getArtifacts().add(artifact);
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        doc.save(out, com.aspose.pdf.SaveFormat.Pdf);
        out.close();
    }

    // 注意 pdf 存在找不到字体的问题 因为字体库是以文件名查找 而不是字体名
    private static String getFontName(String font) {
        switch (font.trim().toLowerCase()) {
            case "宋体":
                return "simsun";
            case "微软雅黑":
                return "simhei";
            default:
                return font;
        }
    }
}